<!--
 * @Description: 预览债转证明
 * @Author gong
 * @create 2024/9/13 10:19
 -->
<!--setup-->
<script setup>
import { onMounted, onUnmounted, getCurrentInstance, ref } from 'vue'
import { to } from 'sf-utils2'
import cfDebtTransferAgreementApi from '@/api/modules/cf-debt-transfer-agreement'
import { ElMessage } from 'element-plus'
import profile from '@root/profile' // 配置文件

const { proxy } = getCurrentInstance()
const props = defineProps({
  // 项目id
  prjId: {
    type: String,
    default: () => ''
  }
})
const emit = defineEmits([])

/* 状态 */
const pageData = ref({}) // 债权转让协议数据
const myIframeRef = ref(null)
const markObj = ref({ pageNum: 1, pageSize: 10 }) // 表单分页参数

/* 方法 */
/**
 * 获取预览数据并传递
 * @returns {Promise<MessageHandler>}
 */
const getPreviewData = async () => {
  const params = {
    ...markObj.value,
    prjId: props.prjId // 项目id
  }
  const [res, err] = await to(cfDebtTransferAgreementApi.previewDebtTraAgr(params))
  if (err || res?.code !== 200) return ElMessage.error(res?.message || String(err))
  pageData.value = res.data || {}

  let iframe = myIframeRef.value

  iframe.contentWindow.postMessage(JSON.stringify(pageData.value), profile.zsamcH5Address)
}

/**
 * 监听iframe内返回的消息
 * @param e
 */
const onMessage = (e) => {
  if (profile.zsamcH5Address.includes(e.origin)) {
    markObj.value = JSON.parse(e.data)
    getPreviewData()
  }
}

/* 计算 */

/* 监听 */

/* 周期 */
onMounted(() => {
  window.addEventListener('message', onMessage)
})

onUnmounted(() => {
  window.removeEventListener('message', onMessage)
})

/* 暴露 */
defineExpose({
  $: proxy.$
})
</script>

<!--render-->
<template>
  <div class="page">
    <!-- 内容区 -->
    <iframe
      ref="myIframeRef"
      :src="`${profile.zsamcH5Address}/#/TransferNoticePreview`"
    />
  </div>
</template>

<!--style-->
<style scoped lang="less">
.page {
  height: 100%;

  iframe {
    width: 100%;
    height: 100%;
  }
}
</style>
